<?php

namespace Controller\Article;

class Add extends \Controller\Base {

	public function actionIndex() {
		$this->setMenuPath('Article', 'Lists');
		$all = \Data\Category::instance()->getLevelCategories();
		$id = $this->getInt('id');
		$data = null;
		if ($id) {
			$data = \Data\Article::instance()->getOneById($id);
		}
		if (!$data) {
			$data = array(
				'CategoryId' => '',
				'Title' => '',
				'Source' => '',
				'Content' => '',
			);
		}
		if ($this->isPost()) {
			$saveData = $this->doSave();
			$data = $saveData ? $saveData : $data;
		}
		$this->assign('data', $data);
		$this->assign('all', $all);
		$this->display();
	}

	private function doSave() {
		$data['CategoryId'] = $this->postInt('categoryId');
		$data['Title'] = $this->postParam('title');
		$data['Source'] = $this->postParam('source');
		$data['Content'] = $this->postParam('content');
		if (!$data['Title']) {
			$this->addErrorMsg('请选择标题');
			return $data;
		}
		if (!$data['CategoryId']) {
			$this->addErrorMsg('请选择分类');
			return $data;
		}
		if (!$data['Content']) {
			$this->addErrorMsg('请输入内容');
			return $data;
		}
		$id = $this->postInt('id');
		if (!$id) {
			\Data\Article::instance()->addArticle($data);
			\Lib\Util\Comm::redirect('/Article/Lists');
		} else {
			\Data\Article::instance()->updateArticle($id, $data);
			$this->addSuccessMsg('修改成功');
		}
		return $data;
	}
}